const path = require("path");
const koa = require("koa2");
const app = new koa();
const json = require("koa-json");
const compress = require("koa-compress");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const cors = require("koa2-cors");
const static = require("koa-static");
const FLayout = require("./util/FLayout");
const format = require("string-format");
format.extend(String.prototype);

const staticPath = "./hubs";
app.use(static(path.join(__dirname, staticPath)));

// error-handling
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    FLayout.layout(err, ctx);
  }
});

// middlewares
app.use(
  compress({
    filter: function(content_type) {
      return /text/i.test(content_type);
    },
    threshold: 2048,
    flush: require("zlib").Z_SYNC_FLUSH
  })
);

app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"]
  })
);

app.use(json());
app.use(logger());

// cors()
// if (process.env.NODE_ENV === "production") {
//   app.use(cors());
// }
app.use(cors());

// routes
require("./routes/index")(app);

module.exports = app;
